package week5th;

public class ProductList {
    protected int count;
    protected LinearNode<Product> head, tail;
    protected int NOT_FOUND = -1;

    public ProductList() {
        count = 0;
        head = tail = null;
    }

    public void add(Product element) {
        LinearNode<Product> current = head;
        LinearNode<Product> node = new LinearNode(element);
        if (head == null)
            head = node;
        else {
            while (current.getNext() != null) {
            current = current.getNext();
            }
            current.setNext(node);
        }
        count++;
    }

    public void addToFront(Product element) {
        LinearNode<Product> node = new LinearNode<>(element);
        node = head;
        head = head.getNext();
    }

    public int find(Product element) {
        int index = NOT_FOUND;
        LinearNode<Product> current = head;
        LinearNode<Product> node = new LinearNode<>(element);
        while (current.getNext() != null) {
            index++;
            if (current.getElement().equals(node.getElement()))
                break;
            current = current.getNext();
        }

        return index;
    }

    public Product remove(int index) {
        LinearNode<Product> current = head;
        LinearNode<Product> node;
        for (int i = 0; i < index - 1; i ++) {
            current = current.getNext();
        }
        node = current;
        current.setNext(current.getNext().getNext());
        return node.getElement();
    }

    public Product remove(Product element) {
        int index = find(element);
        return remove(index);
    }

    public void selectionSort() {
        LinearNode<Product> current = head;
        LinearNode<Product> temp,temp2,temp3 = null;
        Product pro = new Product();
        while(current.getNext() != null) {
            temp2 = null;
            temp3 = temp = current;
            while(temp.getNext() != null){
                if(temp.getNext().getElement().compareTo(temp3.getElement()) < 0){
                    temp3 = temp2 = temp.getNext();
                    pro = temp.getNext().getElement();
                }
                temp = temp.getNext();
            }
            if(temp2 != null){
                temp2.setElement(current.getElement());
                current.setElement(pro);
            }

            current = current.getNext();
        }
    }

    public boolean isEmpty() {
        if (count == 0)
            return true;
        else
            return false;
    }

    @Override
    public String toString() {
        String str = "";
        LinearNode<Product> current = head;
        str += current.getElement().toString() + "\n";
        while (current.getNext() != null) {
            current = current.getNext();
            str += current.getElement().toString() + "\n";
        }
        str += "\n";
        return str;
    }
}
